package bll

import (
	"context"
	"encoding/json"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	string_ "github.com/alibabacloud-go/darabonba-string/client"
	time "github.com/alibabacloud-go/darabonba-time/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	log "maya-service/collector/logger"
	"maya-service/event"
	modelEvent "maya-service/model/event"
)

func init() {
	event.Subscribe(event.SupervisorAllocateSuccess, func(ctx context.Context, e event.Event, payload interface{}) {
		data, ok := payload.(*modelEvent.SupervisorAllocate)
		if !ok {
			return
		}

		err := SendSms(data.UserName, data.SupervisorPhoneNumber)
		if err != nil {
			log.Error(fmt.Sprintf("send sms error: %s", err.Error()))
		} else {
			log.Info(fmt.Sprintf("%v send sms success: %s", data.UserName, data.SupervisorPhoneNumber))
		}
		return
	})
}

// 使用AK&SK初始化账号Client
func CreateClient(accessKeyId string, accessKeySecret string) (_result *dysmsapi.Client, _err error) {
	config := &openapi.Config{}
	config.AccessKeyId = &accessKeyId
	config.AccessKeySecret = &accessKeySecret
	_result = &dysmsapi.Client{}
	_result, _err = dysmsapi.NewClient(config)
	return _result, _err
}

// SendSms 发送短信
func SendSms(nickName string, phoneNumber string) (_err error) {
	data, _ := json.Marshal(struct {
		Nickname string `json:"nickname"`
	}{
		Nickname: nickName,
	})
	args := tea.StringSlice([]string{
		phoneNumber,
		"莘古",
		"SMS_475810289",
		string(data),
	})

	client, _err := CreateClient("LTAI5tQ4b6owYh2xLLdkTNB1", "9JPvn0KFskAulkzt7p27trUgGxltJs")
	if _err != nil {
		return _err
	}

	// 1.发送短信
	sendReq := &dysmsapi.SendSmsRequest{
		PhoneNumbers:  args[0],
		SignName:      args[1],
		TemplateCode:  args[2],
		TemplateParam: args[3],
	}
	sendResp, _err := client.SendSms(sendReq)
	if _err != nil {
		return _err
	}

	code := sendResp.Body.Code
	if !tea.BoolValue(util.EqualString(code, tea.String("OK"))) {
		log.Error(fmt.Sprintf("错误信息: " + tea.StringValue(sendResp.Body.Message)))
		return _err
	}

	bizId := sendResp.Body.BizId
	// 2. 等待 10 秒后查询结果
	_err = util.Sleep(tea.Int(10000))
	if _err != nil {
		return _err
	}
	// 3.查询结果
	phoneNums := string_.Split(args[0], tea.String(","), tea.Int(-1))
	for _, phoneNum := range phoneNums {
		queryReq := &dysmsapi.QuerySendDetailsRequest{
			PhoneNumber: util.AssertAsString(phoneNum),
			BizId:       bizId,
			SendDate:    time.Format(tea.String("yyyyMMdd")),
			PageSize:    tea.Int64(10),
			CurrentPage: tea.Int64(1),
		}
		queryResp, _err := client.QuerySendDetails(queryReq)
		if _err != nil {
			return _err
		}

		dtos := queryResp.Body.SmsSendDetailDTOs.SmsSendDetailDTO
		// 打印结果
		for _, dto := range dtos {
			if tea.BoolValue(util.EqualString(tea.String(tea.ToString(tea.Int64Value(dto.SendStatus))), tea.String("3"))) {
				log.Info(fmt.Sprintf("%v  发送成功，接收时间: %v", tea.StringValue(dto.PhoneNum), tea.StringValue(dto.ReceiveDate)))
			} else if tea.BoolValue(util.EqualString(tea.String(tea.ToString(tea.Int64Value(dto.SendStatus))), tea.String("2"))) {
				log.Info(fmt.Sprintf("%v  发送失败", tea.StringValue(dto.PhoneNum)))
			} else {
				log.Info(fmt.Sprintf("%v  正在发送中...", tea.StringValue(dto.PhoneNum)))
			}
		}
	}
	return _err
}
